package com.ljf.config.domain.service;

import com.ljf.common.domain.service.BasisDomainService;
import com.ljf.common.exception.ServiceException;
import com.ljf.common.utils.StringUtil;
import com.ljf.config.domain.repository.ConfigDatKeyValueRepository;
import com.ljf.config.dto.command.ConfigDatKeyValueCommand;
import com.ljf.config.dto.query.ConfigDatKeyValueQuery;
import com.ljf.config.model.ConfigDatKeyValue;
import com.ljf.config.vo.ConfigDatKeyValueVO;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 配置中心  领域服务
 *
 * @author LJF
 * @since 2024-12-17
 */
@Component
public class ConfigDatKeyValueDomainService extends BasisDomainService<ConfigDatKeyValueRepository, ConfigDatKeyValueQuery, ConfigDatKeyValueVO, ConfigDatKeyValue, ConfigDatKeyValueCommand> {

    /**
     * 通过关键字查询列表
     *
     * @param belongService
     * @param tableKey
     * @param businessKey
     * @return
     * @throws ServiceException
     */
    public List<String> getListByKey(String belongService, String tableKey, String businessKey) throws ServiceException {
        String key = this.getStringByKey(belongService, tableKey, businessKey);
        return new ArrayList<>(Arrays.asList(key.split(",")));
    }

    /**
     * 通过关键字查询字符串
     *
     * @param belongService
     * @param tableKey
     * @param businessKey
     * @return
     * @throws ServiceException
     */
    public String getStringByKey(String belongService, String tableKey, String businessKey) throws ServiceException {
        if (StringUtil.isEmpty(belongService) || StringUtil.isEmpty(tableKey) || StringUtil.isEmpty(businessKey)) {
            throw new ServiceException("获取配置异常:缺少关键字");
        }
        ConfigDatKeyValueVO configData = repository.selectOne(
                ConfigDatKeyValueQuery.builder()
                        .belongService(belongService)
                        .tableKey(tableKey)
                        .businessKey(businessKey)
                        .build()
        );
        if (StringUtil.isEmpty(configData.getValue())) {
            throw new ServiceException("获取配置异常:不存在对应配置");
        }
        return configData.getValue();
    }

}
